﻿using LuShanTea.Admin.Web.App_Start;
using LuShanTea.Admin.Web.Models;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LuShanTea.Admin.Web.Controllers
{
    public class CityController : Controller
    {
        public ICityService CityService { get; set; }

        public IProvinceService ProvinceService { get; set; }

        // GET: City
        [CheckPermission("City.List")]
        public ActionResult List()
        {
            var model = CityService.GetAll();
            return View(model);
        }
        [HttpPost]
        [CheckPermission("City.Delete")]
        public ActionResult Delete(long id)
        {
            CityService.MarkDelete(id);
            return Json(new AjaxResult { Status = "ok" });
        }
        [HttpGet]
        [CheckPermission("City.AddNew")]
        public ActionResult AddNew()
        {
            var model = ProvinceService.GetAll();
            return View(model);
        }

        [HttpPost]
        [CheckPermission("City.AddNew")]
        public ActionResult AddNew(CityAddModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) });
            }
            var en = CityService.GetByName(model.Name);
            if (en != null)
            {
                if (en.ProId == model.ProvId)
                {
                    return Json(new AjaxResult { Status = "error", ErrorMsg = "该省已存在该市" });
                }
            }
            CityService.AddNew(model.Name, model.ProvId);
            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpGet]
        [CheckPermission("City.Edit")]
        public ActionResult Edit(long id)
        {
            CityEditListModel model = new CityEditListModel();
            model.Provs = ProvinceService.GetAll();
            model.City = CityService.GetById(id);
            return View(model);
        }
        [HttpPost]
        [CheckPermission("City.Edit")]
        public ActionResult Edit(CityEditModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) });
            }
            var en = CityService.GetByName(model.Name);
            if (en != null)
            {
                if (en.ProId == model.ProvId)
                {
                    return Json(new AjaxResult { Status = "error", ErrorMsg = "该省已存在该市" });
                }
            }
            CityService.Update(model.Id, model.Name, model.ProvId);
            return Json(new AjaxResult { Status = "ok" });
        }

    }
}